package util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {


    public static String request(String api ){//访问的静态方法

        HttpURLConnection connection = null;//连接对象
        int responseCode = 0;//响应码
        try{
            URL url = new URL(api);//获取api的URL对象
            //获取对应的连接对象
            connection = (HttpURLConnection) url.openConnection();
            responseCode = connection.getResponseCode();//获取连接的响应码
        }catch (Exception e){
            e.printStackTrace();
        }

        if(200 <= responseCode && responseCode<=299){//正常响应
            try(InputStream inputStream = connection.getInputStream();//获取输入流
                BufferedReader in =  new BufferedReader(new InputStreamReader(inputStream));//读取输入流中的内容
            ){

                StringBuilder response = new StringBuilder();//创建一个字符串对象,用于存储响应内容
                String currentLine;

                while ((currentLine = in.readLine())!= null){//逐行读取内容
                    response.append(currentLine);
                }

                String result = response.toString();
                return result;

            }catch (Exception e){
                e.printStackTrace();
            }


        }

        return null;


    }

}
